const { Component } = React;

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { clickCount: 0 };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({ clickCount: prevState.clickCount + 1 }));
  }

  render() {
    return (
      <h2
        onClick={this.handleClick}
        style={{ userSelect: "none", cursor: "pointer" }}
      >
        点我！点击次数为: {this.state.clickCount}
      </h2>
    );
  }
}

class HelloOpacity extends React.Component {
  constructor(props) {
    super(props);
    this.state = { opacity: 1.0 };
  }

  componentDidMount() {
    this.timer = setInterval(
      function() {
        var opacity = this.state.opacity;
        opacity -= 0.05;
        if (opacity < 0.1) {
          opacity = 1.0;
        }
        this.setState({
          opacity: opacity
        });
      }.bind(this),
      100
    );
  }

  render() {
    return (
      <div style={{ opacity: this.state.opacity }}>Hello {this.props.name}</div>
    );
  }
}

class Button extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: 0 };
    this.setNewNumber = this.setNewNumber.bind(this);
  }

  setNewNumber() {
    this.setState({ data: this.state.data + 1 });
  }
  render() {
    return (
      <div>
        <button onClick={this.setNewNumber}>INCREMENT</button>
        <Content myNumber={this.state.data} />
      </div>
    );
  }
}

class Content extends React.Component {
  componentWillMount() {
    console.log("Component WILL MOUNT!");
  }
  componentDidMount() {
    console.log("Component DID MOUNT!");
  }
  componentWillReceiveProps(newProps) {
    console.log("Component WILL RECEIVE PROPS!");
  }
  shouldComponentUpdate(newProps, newState) {
    return true;
  }
  componentWillUpdate(nextProps, nextState) {
    console.log("Component WILL UPDATE!");
  }
  componentDidUpdate(prevProps, prevState) {
    console.log("Component DID UPDATE!");
  }
  componentWillUnmount() {
    console.log("Component WILL UNMOUNT!");
  }

  render() {
    return (
      <div>
        <h3>{this.props.myNumber}</h3>
      </div>
    );
  }
}

class App extends Component {
  render() {
    return (
      <div>
        <a href="https://www.runoob.com/react/react-component-api.html">
          https://www.runoob.com/react/react-component-api.html
        </a>
        <Counter />
        <HelloOpacity />
        <Button />
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));
